<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="name" label="模板名称" required>
        <uni-easyinput placeholder="请输入模板名称" v-model="formData.name"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="width" label="模板宽度" required>
        <uni-easyinput placeholder="请输入宽度(px)" type="number" v-model="formData.width"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="height" label="模板高度" required>
        <uni-easyinput placeholder="请输入高度(px)" type="number" v-model="formData.height"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="photo_count" label="照片数量" required>
        <uni-easyinput placeholder="需要拍摄的照片数量" type="number" v-model="formData.photo_count"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="status" label="是否启用">
        <switch :checked="formData.status === 1" @change="e => formData.status = e.detail.value ? 1 : 0" />
        <text class="status-text">{{formData.status === 1 ? '启用' : '禁用'}}</text>
      </uni-forms-item>
      <uni-forms-item name="create_date" label="创建时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.create_date"></uni-datetime-picker>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <button class="uni-button" style="width: 100px; margin-left: 15px;" @click="goBack">返回</button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/a-templates.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'a-templates';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  export default {
    data() {
      let formData = {
        "name": "",
        "width": 2400,
        "height": 3600,
        "photo_count": 3,
        "slots": [],
        "background_images": [],
        "thumbnail_url": "",
        "status": 1,
        "sort": 100,
        "create_date": new Date().getTime()
      }
      return {
        formData,
        formOptions: {},
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 确保保存其他必要字段的默认值
        value.slots = []
        value.background_images = []
        value.thumbnail_url = ""
        value.sort = 100
        
        // 确保create_date是时间戳格式
        if (value.create_date && typeof value.create_date === 'string') {
          // 如果是字符串格式，转换为时间戳
          value.create_date = new Date(value.create_date).getTime()
        } else if (!value.create_date) {
          // 如果未设置，使用当前时间戳
          value.create_date = new Date().getTime()
        }
        
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },
      
      /**
       * 返回列表页
       */
      goBack() {
        uni.redirectTo({
          url: '/pages/a-templates/list'
        })
      }
    }
  }
</script>

<style>
.uni-container {
  padding: 15px;
}
.uni-button-group {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
.status-text {
  margin-left: 10px;
  color: #666;
}
</style>
